package com.xinchao.ck_mips.utils.download;

import android.os.Handler;

/**
 * Created by zhangbw on 2018/9/28.
 */

public class MultiThreadListener implements OkHttpDownloadListener {
    private MultiThreadDownload mMultiThreadDownload;
    private MultiThreadBean mMultiThreadBean;
    private Handler mHandler;

    public MultiThreadListener(MultiThreadDownload multiThreadDownload,MultiThreadBean multiThreadBean, Handler handler) {
        mMultiThreadDownload = multiThreadDownload;
        mMultiThreadBean = multiThreadBean;
        mHandler = handler;
    }

    @Override
    public void onDownloadSuccess(String localFileName) {
        mMultiThreadBean.downloadStatus = MultiThreadBean.DOWNLOADED;
        mHandler.obtainMessage().sendToTarget();
        if (mMultiThreadDownload != null) {
            mMultiThreadDownload.onDownloadSuccess(mMultiThreadBean, localFileName);
        }
    }

    @Override
    public void onDownloadFailed(Throwable throwable) {
        if (mMultiThreadBean.retryCount < 3) {
            mMultiThreadBean.retryCount++;
            mMultiThreadBean.downloadStatus = MultiThreadBean.DOWNLOADINIT;
            mHandler.obtainMessage().sendToTarget();
            return;
        }
        mMultiThreadBean.downloadStatus = MultiThreadBean.DOWNLOADFAILED;
        if (mMultiThreadDownload != null) {
            mMultiThreadDownload.onDownloadFailed(mMultiThreadBean, throwable);
        }
    }

    @Override
    public void onStart(long max) {
        mMultiThreadBean.fileTotalLength = max;
        if (mMultiThreadDownload != null) {
            mMultiThreadDownload.onStart(mMultiThreadBean, max);
        }
    }

    @Override
    public void onDownloading(long currentSize) {
        mMultiThreadBean.fileDownloadedLength = currentSize;
        if (mMultiThreadDownload != null) {
            mMultiThreadDownload.onDownloading(mMultiThreadBean, currentSize);
        }
    }
}
